import { validateNull } from '/@/utils/validate';
import { h } from 'vue';
import { ElNotification, ElButton } from 'element-plus';
import { useRouter, useRoute } from 'vue-router';
import { fetchList } from '/@/api/platform/alarmLogging';
import { useAlarm } from '/@/stores/alarm';
import mittBus from '/@/utils/mitt';
export const useCheckAlarm = (audioRef: any) => {
	const router = useRouter();
	const route = useRoute();
	const alarmState = reactive<{ alarmList: any; countAlarm: number }>({
		alarmList: [],
		countAlarm: 0,
	});
	const ElNotificationRef = ref();
	const refreshTimer = ref();
	const showNotify = (record: any) => {
		ElNotificationRef.value && ElNotificationRef.value?.close();
		ElNotificationRef.value = ElNotification({
			title: '报警提醒',
			dangerouslyUseHTMLString: true,
			position: 'bottom-right',
			type: 'warning',
			duration: 0,
			// offset: 200,
			message: h('div', [
				h('div', { class: 'py-2' }, [
					h('div', [h('span', '安装地点：'), h('span', { class: 'text-error' }, `${record?.address || '--'}`)]),
					h('span', { class: 'text-primary' }, `${record?.equipmentName || '--'}`),
					h('span', '设备发生报警，请立即处理!'),
				]),
				h(
					ElButton,
					{
						type: 'primary',
						onClick: () => {
							handleAlarm(record);
						},
					},
					() => '立即查看'
				),
				h(ElButton, { type: 'info', onClick: handleClose }, () => '我已知晓'),
			]),
		});
		audioRef.value?.play(); //播放音频
	};
	const handleClose = () => {
		ElNotificationRef.value?.close();
	};
	// 刷新当前 tagsView
	const refreshCurrentTagsView = () => {
		mittBus.emit('onCurrentContextmenuClick', Object.assign({}, { contextMenuClickId: 0, ...route }));
	};
	const handleAlarm = (record: any) => {
		handleClose();
		const { path, query } = route;
		// 如果当前是宝记录页面，是相同的一台设备报警，刷新当前页面
		if (path === '/platform/alarmLogging/index' && query?.equipmentId === record.equipmentId && query?.siteId === record.siteId) {
			refreshCurrentTagsView();
		} else {
			router.push({
				path: '/platform/alarmLogging/index',
				query: {
					equipmentId: record?.equipmentId,
					siteId: record?.siteId,
				},
			});
		}
	};
	const getAlarm = async () => {
		const res = await fetchList({ eventStatus: 10, descs: 'create_time' });
		if (validateNull(res) || res.code === 1) {
			clearInterval(refreshTimer.value); // 发生异常关闭定时器
			return;
		}
		alarmState.countAlarm = res.data.total || 0;
		alarmState.alarmList = res.data.records || [];
		useAlarm().setAlarmCount(res.data.total || 0);
		if (res.data.total > 0) {
			showNotify(res.data.records[0]);
		} else {
			handleClose();
		}
	};
	const refreshAlarm = () => {
		refreshTimer.value = setInterval(() => {
			getAlarm();
		}, 1000 * 60);
	};
	return { ...toRefs(alarmState), refreshTimer, ElNotificationRef, getAlarm, refreshAlarm, showNotify, handleAlarm };
};
